package com.xyzboom.web.servlets.course;

import com.xyzboom.database.dao.HitCourseDAO;
import com.xyzboom.database.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@WebServlet(name = "ExitCourse", urlPatterns = "/servlets/course/ExitCourse")
public class ExitCourse extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public static final String SUCCESS_CODE = "退选成功";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        if (request.getParameter("exit") == null) {
            response.getWriter().print("请求有误！");
            return;
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.getWriter().print("您需要登录！");
            return;
        }
        Enumeration<String> parameters = request.getParameterNames();
        List<Integer> courseIds = new ArrayList<>();
        while (parameters.hasMoreElements()) {
            String parameter = parameters.nextElement();
            int id;
            try {
                id = Integer.parseInt(parameter);
                courseIds.add(id);
            } catch (NumberFormatException ignore) {
            }
        }
        try {
            if (HitCourseDAO.removeHitCourse(user.getId(), courseIds) > 0) {
                response.getWriter().print(SUCCESS_CODE);
            } else {
                response.getWriter().print("没有成功退选！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().print("数据库错误！");
        }
    }
}
